package java_class_work.week07.loginDemo01;

import java_class_work.week07.JDBCUtils;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @Auther: admin
 * @Date: 2022/10/24 17:31
 * @Description:
 */

public class Login {
    public static void main(String[] args) {
        int state = certify(loginUI());
        // 映射
        Map<Integer, String> hm = new HashMap<>(4);
        hm.put(-2, "数据库异常");
        hm.put(-1, "密码错误");
        hm.put(0, "无此用户");
        hm.put(1, "登录成功");
        System.out.println(hm.get(state));
    }

    /**
     * @param inUser
     * @return 0无用户
     * 1成功
     * -1失败
     * -2 其他异常
     */
    static int certify(Map<String, String> inUser) {
        // 获取连接
        Connection con = JDBCUtils.getConnection();
        // 获取输入的用户名
        String uname = inUser.get("username");

        String sql = "select *,count(*) from user where username = ?";
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = con.prepareStatement(sql);
            ps.setString(1, uname);
            rs = ps.executeQuery();
            // 如何获取返回结果集的行数?
            rs.next();
            if (rs.getInt("count(*)") == 0) {
                return 0;
            }
            if (inUser.get("password").equals(rs.getString("password"))) {
                return 1;
            } else {
                return -1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
                if (ps != null) ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return -2;
    }


    static Map<String, String> loginUI() {
        HashMap<String, String> hm = new HashMap<>();
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入账号：");
        String user = scanner.nextLine();
        System.out.print("请输入密码：");
        String pwd = scanner.nextLine();
        hm.put("username", user);
        hm.put("password", pwd);
        return hm;
    }
}
